<?php 
session_start();

$username = isset($_POST['username'])? trim($_POST['username']) : "";
$password = isset($_POST['password'])? trim($_POST['password']) : "";
$remeber_me = isset($_POST['remeber_me'])? trim($_POST['remeber_me']) : "";

if($username=="" || $password==""){
    $_SESSION['LOGIN_ERROR'] = "用户名和密码不能为空！";
    header("Location: login.php");
}

else{
    // 到数据库里检索是否存在此用户且密码正确。
    require("db.php");
    $rows = $db->query("select * from users where username='$username'");
    if($rows!==FALSE && $rows->rowCount()>0){
        $user = $rows->fetch();
        if(password_verify($password,$user['password'])){
            // 登录验证成功后
            $_SESSION['username'] = $username;
            $_SESSION['name'] = $user['name'];
            unset($_SESSION['LOGIN_ERROR']);
            if($remeber_me){
                setcookie("username",$username,time()+(30*24*60*60));
                setcookie("password",$password,time()+(30*24*60*60));
            }
            else{
                setcookie("username",$username,time()-(30*24*60*60));
                setcookie("password",$password,time()-(30*24*60*60));
            }
            header("Location: index.php");
            exit;
        }
        $_SESSION['LOGIN_ERROR'] = "用户名或密码错误！";
        header('Location: login.php');
        exit;
    }
    $_SESSION['LOGIN_ERROR'] = "用户名或密码错误！";
    header("Location: login.php");

} 